<template>
  <div>
    <el-form :model="basicInfo" :rules="rules" ref="basicInfo" class="demo-ruleForm">
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>发放基础信息</h4>
          <el-form-item label="所属分公司" label-width="180px" required>
            <el-select v-if="!brachDisabled" v-model="basicInfo.branchId" :disabled="brachDisabled"
            @change="getDeptList" @visible-change="visibleChange" style="width:240px" placeholder="分公司">
              <el-option v-for="(item, index) in this.branchList" :value="item.branch_Id" :label="item.branch_Name" :key="index"></el-option>
            </el-select>
            <el-input v-if="brachDisabled" v-model="showBranch" :disabled="brachDisabled" style="width:240px"></el-input>
          </el-form-item>
          <el-form-item label="所属部门" label-width="180px" prop="departmentId" required>
            <el-select v-if="!brachDisabled" v-model="basicInfo.departmentId" :disabled="brachDisabled" placeholder="所属部门" style="width:240px">
              <el-option v-for="(item, index) in this.deptList" :value="item.org_id" :label="item.org_name" :key="index"></el-option>
            </el-select>
            <el-input v-if="brachDisabled" v-model="this.showDept" disabled style="width:240px"></el-input>
          </el-form-item>
          <el-form-item label="客资类型" label-width="180px" prop="userType">
            <el-select v-model="basicInfo.userType" style="width:240px" placeholder="客资类型" :loading="customerTypeLoading">
              <!-- <el-option value="1" label="普通超市"></el-option> -->
              <el-option v-for="(item, index) in customerTypeList"
              :key="index"
              :label="item.name"
              :value="item.id.toString()"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="促销费用" label-width="180px" prop="feeId">
            <!-- <el-input v-model="basicInfo.feeId" style="width:220px"></el-input> -->
            <el-select v-model="basicInfo.feeId" @change="handleChangeSalesCosts" placeholder="请选择促销费用" style="width:240px" :loading="saleCostLoading">
              <el-option v-for="(item, index) in salesCostsList" :key="index" :label="item.promotionName" :value="item.id.toString()" ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="this.selectSalesCosts.type === 2 || this.selectSalesCosts.type === ''"
          label="供应商占比" label-width="180px" prop="feeProportion">
            <el-input v-model="basicInfo.feeProportion" style="width:240px">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
          <el-form-item label="批次名称" label-width="180px" prop="name">
            <el-input v-model="basicInfo.name" style="width:240px"></el-input>
          </el-form-item>
          <el-form-item label="活动起止时间" label-width="180px" prop="startStopTime">
            <el-date-picker
            v-model="basicInfo.startStopTime" :editable="false"
            type="datetimerange" placeholder="活动起止时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="daterangeFormat($event, '活动')" style="width:360px"
            :picker-options="pickerExpirationDate"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="优惠券有效期" label-width="180px" prop="termType">
            <el-select v-model="basicInfo.termType" style="width:240px" @change="termTypeChange">
              <el-option label="天数" value="1"></el-option>
              <el-option label="时间段" value="2"></el-option>
              <el-option label="截止时间" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="basicInfo.termType === '1'" label="" label-width="180px" prop="dataNum" ref="dataNum">
            <el-input v-model="basicInfo.dataNum" style="width:240px">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="basicInfo.termType === '2'" label="" label-width="180px" prop="dateRange" ref="dateRange">
            <el-date-picker
            type="datetimerange"
            v-model="basicInfo.dateRange"
            style="width:360px"
            :picker-options="pickerExpirationDate"
            @change="daterangeFormat($event, '优惠券')"
            value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item v-if="basicInfo.termType === '3'" label="" label-width="180px" prop="couponEndTime" ref="couponEndTime">
            <el-date-picker v-model="basicInfo.couponEndTime" value-format="yyyy-MM-dd" style="width:240px" :picker-options="pickerExpirationDate">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="充值方式" label-width="180px" prop="type" required>
            <el-radio-group v-model="basicInfo.type">
              <el-radio label="14">每笔</el-radio>
              <el-radio label="15">累计</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- </el-form> -->
        </div>
      </div>
      <div class="detail-info" style="margin-top: 50px">
        <div class="form-item">
          <h4>充值信息</h4>
          <el-button type="primary" @click="addLadder">新增阶梯</el-button>
          <el-table style="width: 100%; margin-top:30px" :data="registerRule" border>
            <el-table-column label="充值区间" align="center">
              <template scope="scope">
                <el-input v-model="scope.row.minAmount" @blur="checkLabber(scope, 'minAmount')" style="width:160px">
                  <template slot="append">元</template>
                </el-input>
                <el-input :disabled="scope.$index === registerRule.length - 1 ? true : false" v-model="scope.row.maxAmount" @blur="checkLabber(scope, 'maxAmount')" style="width:160px;float:right">
                  <template slot="append">元</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="返券比例" align="center">
              <template scope="scope">
                <el-input v-model="scope.row.radio" @blur="checkLabber(scope, 'radio')" style="width:160px">
                  <template slot="append">%</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column prop="couponMax" label="最大面值" align="center">
              <template scope="scope">
                <el-input v-model="scope.row.couponMax" @blur="checkLabber(scope, 'couponMax')" style="width:160px">
                  <template slot="append">元</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template scope="scope">
                <el-button type="text" @click="deleteLabber(scope)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="detail-info">
        <div class="form-item" style="margin-bottom:0">
          <h4>备注</h4>
          <el-input style="width:400px" type="textarea" placeholder="请输入备注" v-model="basicInfo.description"></el-input>
        </div>
      </div>
      <div style="margin: 20px auto 20px; width: 20%">
        <el-button @click="onSubmit(2, 'basicInfo')" type="success">提交</el-button>
        <el-button @click="onSubmit(0, 'basicInfo')" type="warning">暂存</el-button>
        <el-button @click="cancel(menuId, 1)" type="danger">取消</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
  import { getInfo, activity } from '../../../../config/proxy.js'
  import { mapState } from 'vuex'
  import mixins from '../../../../components/mixins.vue'
  export default {
    mixins: [mixins],
    data () {
      var self = this
      var checkGysproportion = (rule, value, callback) => { // 验证供应商占比
        var text = rule.field === 'feeProportion' ? '供应商占比' : '天数'
        if (!value) {
          return callback(new Error(text + '不能为空'))
        } else {
          var reg = /^[0-9]\d*$/
          if (reg.test(value)) {
            value = value.toString()
            if (value.indexOf(0) === 0 && value.length > 1) {
              callback(new Error('不能以0开头'))
            }
            callback()
          } else {
            callback(new Error(text + '必须正整数'))
          }
        }
      }
      return {
        pickerExpirationDate: { // 有效期类型禁用时间段
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptions: {
          disabledDate (time) {
            return time.getTime() < new Date(self.selectSalesCosts.stime).getTime() || time.getTime() > new Date(self.selectSalesCosts.etime).getTime()
          }
        }, // 禁用时间段
        basicInfo: {
          branchId: '', // 分公司
          departmentId: '',
          feeId: '', // 促销费用
          rechargecost: '', // 充值金额
          startTime: '', // 开始时间
          endTime: '', // 结束时间
          startStopTime: '', // 兑换截止日期
          feeProportion: '', // 供应商补差占比
          name: '', // 批次名称
          userType: '1', // 客资类型
          description: '', // 备注
          dateRange: [], // 时间段
          couponStartTime: '', // 开始时间
          couponEndTime: '', // 结束时间
          dataNum: '', // 天数
          termType: '', // 有效期类型 1， 天数 2，时间段 3，截止时间
          type: '' // 充值方式
          // messageTitle: '', // 标题
          // messageContent: '' // 通知内容
        },
        registerRule: [], // 充值信息数组
        // pageLoading: false,
        showBranchName: '', // 页面展示的公司名称
        showDeptName: '', // 页面展示的部门名称
        saleCostLoading: true, // 促销费用加载
        customerTypeLoading: true, // 客资类型加载
        salesCostsList: [], // 促销费用数组
        selectSalesCosts: {}, // 选中的促销费用
        customerTypeList: [], // 客资类型
        validity: '', // 有效期
        description: '', // 备注
        isCreateOrUpdate: '',
        text: '',
        menuId: '',
        // subDisabled: false,
        rules: {
          departmentId: [ // 促销费用
            {required: true, type: 'number', message: '请选择所属部门', trigger: 'change'}
          ],
          feeId: [ // 促销费用
            {required: true, message: '请选择促销费用', trigger: 'change'}
          ],
          userType: [ // 客资类型
            {required: true, message: '请选择客资类型', trigger: 'change'}
          ],
          feeProportion: [ // 供应商占比
            {validator: checkGysproportion, trigger: 'blur'}
          ],
          name: [ // 批次名称
            {required: true, message: '请输入批次名称', trigger: 'blur'},
            { min: 0, max: 16, message: '长度不能超过16个字符', trigger: 'blur' }
//            {required: true, message: '请输入批次名称', trigger: 'change'}
          ],
          type: [ // 客资类型
            {required: true, message: '请选择充值方式', trigger: 'change'}
          ],
          dataNum: [ // 天数
            {required: true, message: '请输入天数', trigger: 'blur'},
            {validator: checkGysproportion, trigger: 'blur'}
          ],
          dateRange: [ // 时间段
            {required: true, message: '请选择时间段', trigger: 'change'}
          ],
          couponEndTime: [ // 截止时间
            {required: true, message: '请选择截止时间', trigger: 'change'}
          ],
          termType: [ // 客资类型
            {required: true, message: '请选择优惠券有效期类型', trigger: 'change'}
          ],
          startStopTime: [ // 截止日期
            {type: 'array', required: true, message: '请选择活动起止日期', trigger: 'change'}
          ]
        },
        showBranch: '',
        showDept: '',
        newBranchId: '',
        createBranchId: '',
        brachDisabled: false,
        deptList: [],
        visible: false,
        labberValid: false // 阶梯验证
      }
    },
    methods: {
      getDeptList (val) { // 获取部门
        console.log(this.visible)
        this.searchSalesCosts()
        if (this.visible === true) {
          console.log('aaa')
          this.basicInfo.departmentId = ''
          this.basicInfo.feeId = ''
        }
        var _data = {}
        var self = this
        setTimeout(() => {
          console.log(self.branchList)
          self.branchList.forEach(element => {
            if (val === element.branch_Id) {
              console.log(val === element.branch_Id)
              _data.orgId = element.org_id
              self.newBranchId = element.org_id
            }
          })
          console.log(_data)
          if (JSON.stringify(_data) === '{}') {
            return
          } else {
            getInfo.department(_data, (res) => {
              console.log(res)
              if (res.message === 'ok') {
                if (val === 1) {
                  self.deptList = []
                  res.content.forEach(element => {
                    if (element.org_name.indexOf('公司') === -1) {
                      self.deptList.push(element)
                    }
                  })
                  self.matchDept()
                } else {
                  self.deptList = res.content
                  self.matchDept()
                }
              } else {
                self.message(res.message, 'error')
              }
            })
          }
        }, 500)
      },
      matchDept () { // 匹配 当前登录人的部门与部门列表
        console.log(this.deptList)
        for (let index = 0; index < this.deptList.length; index++) {
          const element = this.deptList[index]
          // console.log(Number(this.basicInfo.departmentId) === Number(element.org_id))
          // console.log(Number(this.basicInfo.departmentId), Number(element.org_id))
          if (Number(this.basicInfo.departmentId) === Number(element.org_id)) {
            return
          } else {
            if (index === this.deptList.length - 1) {
              this.basicInfo.departmentId = ''
            }
          }
        }
      },
      visibleChange (a) {
        console.log(a)
        this.visible = a
      },
      termTypeChange (val) { // 优惠券有效期
        console.log(val)
        console.log(this.$refs)
        switch (val) {
          case '1':
            if (this.$refs.dateRange) {
              this.$refs.dateRange.resetField()
            }
            if (this.$refs.couponEndTime) {
              this.$refs.couponEndTime.resetField()
            }
            this.basicInfo.dateRange = []
            break
          case '2':
            if (this.$refs.dataNum) {
              this.$refs.dataNum.resetField()
            }
            if (this.$refs.couponEndTime) {
              this.$refs.couponEndTime.resetField()
            }
            this.basicInfo.dataNum = ''
            break
          case '3':
            if (this.$refs.dataNum) {
              this.$refs.dataNum.resetField()
            }
            if (this.$refs.dateRange) {
              this.$refs.dateRange.resetField()
            }
            this.basicInfo.dataNum = ''
            this.basicInfo.couponStartTime = ''
            break
          default:
            break
        }
      },
      searchCustomerType () { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
          }
        })
      },
      searchSalesCosts () { // 查询促销费用
        var _data = {
          branchId: this.basicInfo.branchId,
          activityType: '-1'
        }
        activity.cxfy.allList(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.salesCostsList = res.content
            this.saleCostLoading = false
            // this.pageLoading = false
            // if (id) {
            //   this.searchDetail(id)
            // }
          }
        })
      },
      handleChangeSalesCosts (val) { // 选择促销费用
        for (var index = 0; index < this.salesCostsList.length; index++) {
          var element = this.salesCostsList[index]
          if (element.id === Number(val)) {
            if (element.promotionType === 1) {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: '',
                etime: ''
              }
              console.log(this.selectSalesCosts)
            } else {
              this.selectSalesCosts = {
                type: element.promotionType,
                stime: this.timeDeltSecond(element.promotionBeginTime),
                etime: this.timeDeltSecond(element.promotionEndTime)
              }
              console.log(this.selectSalesCosts)
            }
          }
        }
      },
      addLadder () { // 新增阶梯
        if (this.registerRule.length < 5) {
          var obj = {
            couponMax: '',
            maxAmount: '',
            minAmount: '',
            radio: ''
          }
          this.registerRule.push(obj)
        } else {
          this.message('最多5级阶梯', 'error')
        }
      },
      deleteLabber (scope) {
        this.$confirm('确定删除该阶梯，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.registerRule.splice(scope.$index, 1)
          if (this.registerRule.length === 1) {
            this.registerRule[0].maxAmount = ''
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      checkLabber (scope, type) { // 验证阶梯
        var index = scope.$index
        var row = scope.row
        this.formVisible(row, index, type)
        // if (this.formVisible(row, index, type)) {
        //   // row.visibleFlag = true
        // } else {
        //   // row.visibleFlag = false
        // }
      },
      formVisible (row) {
        var labberMatch = {
          maxAmount: '充值金额区间',
          minAmount: '充值金额区间',
          radio: '返券比例',
          couponMax: '最大面值'
        }
        var zhengshu = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/
        var zhengzhengshu = /^[+]{0,1}(\d+)$/
        for (let index = 0; index < this.registerRule.length; index++) {
          const element = this.registerRule[index]
          console.log(index)
          console.log(element, 'wwqd')
          for (const key in element) {
            if (element[key] !== '') {
              if (key === 'couponMax') {
                if (!zhengzhengshu.test(element[key])) {
                  this.message(labberMatch[key] + '正整数', 'error')
                  element[key] = ''
                  break
                }
              } else {
                if (!zhengshu.test(element[key])) {
                  this.message(labberMatch[key] + '正数', 'error')
                  element[key] = ''
                  break
                } else if (key === 'radio' && element[key] > 10) {
                  this.message(labberMatch[key] + '小于等于10', 'error')
                  element[key] = ''
                  break
                } else {
                  if ((element.minAmount !== '' && element.radio !== '') && element.minAmount * element.radio / 100 < 1) {
                    this.message('最小值于返券比例相乘后数值必须大等于1', 'error')
                    element.radio = ''
                  }
                  if ((element.minAmount !== '' && element.maxAmount !== '') && Number(element.minAmount) >= Number(element.maxAmount) && index !== this.registerRule.length) {
                    this.message('充值金额区间最大值必须大于最小值', 'error')
                    element.minAmount = ''
                    element.maxAmount = ''
                  }
                  if (this.registerRule.length > 1) {
                    if (this.registerRule.length > 1 && element.maxAmount !== '' && this.registerRule[index + 1].minAmount === '') {
                      this.registerRule[index + 1].minAmount = element.maxAmount
                    }
                    if (element.maxAmount !== '' && this.registerRule[index + 1].minAmount !== '' && element.maxAmount !== this.registerRule[index + 1].minAmount) {
                      this.message('充值金额最大区间于下一个阶梯的最小区间必须相等', 'error')
                      this.forDelete(index + 1)
                    }
                  }
                }
              }
            }
          }
        }
      },
      forDelete (i) { // 循环删除
        for (let index = i; index < this.registerRule.length; index++) {
          const ele = this.registerRule[index]
          for (const key in ele) {
            ele[key] = ''
          }
        }
      },
      searchDetail (row) { // 查询详情
        // console.log(row)
        activity.yhqhd.czfq.detail({id: row.id}, (res) => {
          if (res.message === 'ok') {
            console.log(res)
            // this.pageLoading = false
            this.creatRedeemCodeDetail(res.content)
            this.basicInfo.branchId = res.content.branchId // 创建时公司是返回的公司id
            this.showBranch = res.content.branchName // 创建时公司是返回的公司名称
            this.basicInfo.departmentId = res.content.departmentId // 创建时公司是返回的部门id
            this.showDept = res.content.deptName // 创建时公司是返回的部门名称
            // this.createBranchId = res.content.createBranchId // 创建时 新公司id
            this.searchSalesCosts()
            this.$store.dispatch('pageLoading', false)
          } else {
            this.$store.dispatch('pageLoading', false)
            this.message('查看详情失败', 'error')
          }
        })
      },
      creatRedeemCodeDetail (res) { // 详情回填
        console.log(res, '详情')
        this.basicInfo.feeId = res.feeId.toString() // 促销费用
        this.basicInfo.userType = res.userType.toString() // 客资类型
        this.basicInfo.startStopTime = [res.startTime, res.endTime] // 兑换截止日期
        this.basicInfo.feeProportion = res.feeProportion.toString() // 供应商补差占比
        // this.basicInfo.rechargecost = res.rechargecost.toString() // 充值金额
        this.basicInfo.termType = res.ruleJson.termType.toString() // 有效期类型
        this.basicInfo.type = res.type.toString() // 有效期类型
        this.basicInfo.dataNum = res.ruleJson.dataNum
        this.basicInfo.startTime = res.startTime
        this.basicInfo.endTime = res.endTime
        this.basicInfo.startStopTime = [res.startTime, res.endTime]
        this.basicInfo.name = res.name // 批次名称
        this.basicInfo.description = res.description // 备注
        this.registerRule = res.ruleJson.rule
        this.basicInfo.dateRange = [res.ruleJson.startTime, res.ruleJson.endTime]
        this.basicInfo.couponStartTime = res.ruleJson.startTime
        this.basicInfo.couponEndTime = res.ruleJson.endTime
        res.ruleJson.rule.forEach(element => {
          for (const key in element) {
            if (element[key] !== '' && key !== 'radio') {
              element[key] = (element[key] / 100).toFixed(0)
            }
          }
        })
      },
      creatData (buttonType) { // 创建 提交 _data
        this.basicInfo.feeProportion = this.selectSalesCosts.type === 2 ? this.basicInfo.feeProportion : 0
        // console.log(this.$store.state.tab)
        var dataInfo = {
          // branchName: this.branchName, // 旧分公司名称
          // deptName: this.deptName, // 部门名称
          newBranchId: this.newBranchId, // 新分公司id
          // branchId: this.branchId, // 旧分公司id
          // departmentId: this.deptId, // 部门id
          createBranchId: this.branchOrgId, // 创建人新公司ID
          createUser: this.userName, // 创建人 当前用户
          userId: this.userId,
          id: this.$store.state.tab.uid ? this.$store.state.tab.uid.id : '',
          ptId: this.$store.state.tab.uid ? this.$store.state.tab.uid.ptId : '',
          status: buttonType, // 按钮类型 0 暂存 2 提交
          gwId: this.roleId, // 岗位ID
          uorId: this.uorId // 岗位关系id
        }
        var _data = Object.assign(this.basicInfo, dataInfo)
        _data.registerRule = JSON.parse(JSON.stringify(this.registerRule))
        // _data.registerRule = [...this.registerRule]
        _data.registerRule.forEach(element => {
          for (const key in element) {
            if (element[key] !== '' && key !== 'radio') {
              element[key] = (element[key] * 100).toFixed(0)
            }
          }
        })
        return _data
      },
      onSubmit (buttonType, formName) { // 提交
        this.$refs[formName].validate((valid) => {
          var self = this
          this.formValidation()
          console.log(this.labberValid)
          setTimeout(function () {
            if (valid && self.labberValid === true) {
              var _data = self.creatData(buttonType)
              console.log(_data)
              // self.subDisabled = true
              activity.yhqhd.czfq[self.isCreateOrUpdate](_data, (res) => {
                console.log(res)
                if (res.message === 'ok') {
                  self.cancel(self.menuId)
                  self.message(self.text + '成功', 'success')
                  console.log(self.text)
                  self.$store.dispatch('czfqState', self.$store.state.updateState.czfqState + 1)
                  // self.subDisabled = false
                } else {
                  // self.subDisabled = false
                  self.message(res.message + '失败', 'error')
                }
              })
            } else {
              return false
            }
          }, 100)
        })
      },
      formValidation () {
        if (this.registerRule.length === 0) {
          this.labberValid = false
          this.message('阶梯不能为空', 'error')
          return
        } else {
          for (let index = 0; index < this.registerRule.length; index++) {
            const element = this.registerRule[index]
            if (index === this.registerRule.length - 1) {
              if (element.minAmount !== '' && element.radio !== '' && element.couponMax !== '') {
                console.log('aaa')
                this.labberValid = true
                return
              } else {
                console.log('bbb')
                this.message('第' + (index + 1) + '行阶梯不能为空', 'error')
                this.labberValid = false
                return
              }
            } else {
              for (const key in element) {
                if (element[key] === '') {
                  console.log('ccc')
                  this.message('第' + (index + 1) + '行阶梯不能为空', 'error')
                  this.labberValid = false
                  return
                } else if (element[key] !== '' && key === element.length - 1) {
                  console.log('ddd')
                  this.labberValid = true
                  return
                }
              }
            }
          }
        }
      },
      cancel (id, num) { // 取消
        if (num) {
          this.$confirm('确定要取消？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('delTab', {id: id})
          }).catch(() => {
          })
        } else {
          this.$store.dispatch('delTab', {id: id})
        }
      },
      timeFormat (d, n) { // 时间格式化
        if (d && d !== '') {
          if (n === 'single') {
            this.basicInfo.expirationDate = d
          } else if (n === 'double') {
            return d.split(' - ')
          }
        }
      },
      timeDeltSecond (d) { // 时间去秒
        if (d) {
          return d.split(' ')[0]
        }
      },
      daterangeFormat (t, n) { // 时间段格式化
        console.log(t)
        switch (n) {
          case '活动':
            if (t) {
              this.basicInfo.startTime = t[0]
              this.basicInfo.endTime = t[1]
            } else {
              this.basicInfo.startStopTime = []
              this.basicInfo.startTime = ''
              this.basicInfo.endTime = ''
            }
            break
          case '优惠券':
            if (t) {
              this.basicInfo.couponStartTime = t[0]
              this.basicInfo.couponEndTime = t[1]
            } else {
              this.basicInfo.dateRange = []
              this.basicInfo.couponStartTime = ''
              this.basicInfo.couponEndTime = ''
            }
            break
          default:
            break
        }
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    created () {
      this.menuId = this.$store.state.tab.menuId
      if (this.$store.state.tab.uid) {
        console.log(this.$store.state.tab)
        this.isCreateOrUpdate = 'update'
        this.text = '编辑'
        // this.pageLoading = true
        this.$store.dispatch('pageLoading', true)
        // this.searchSalesCosts(this.$store.state.tab.uid) // 查询促销费用
        this.searchCustomerType() // 查询客资类型
        if (this.branchId === 1) {
          this.brachDisabled = false
        } else {
          this.brachDisabled = true
        }
        this.searchDetail(this.$store.state.tab.uid)
      } else {
        this.isCreateOrUpdate = 'create'
        // this.showBranchName = this.branchName // 新增是公司是当前用户的公司名称
        // this.showDeptName = this.deptName // 新增是公司是当前用户的公司名称
        this.text = '新增'
        if (this.branchId === 1) {
          this.brachDisabled = false
          this.basicInfo.branchId = this.branchId
          this.basicInfo.departmentId = this.deptId
          this.newBranchId = this.branchOrgId
          // this.createBranchId = this.branchOrgId
        } else {
          this.brachDisabled = true
          this.showBranch = this.branchName
          this.showDept = this.deptName
          this.basicInfo.branchId = this.branchId
          this.basicInfo.departmentId = this.deptId
          this.newBranchId = this.branchOrgId
          // this.createBranchId = this.branchOrgId
          // this.formInline.branchId = this.branchId
        }
        this.searchSalesCosts() // 查询促销费用
        this.searchCustomerType() // 查询客资类型
      }
      // console.log(this.isAddOrUpdate)
    },
    computed: mapState({
      userName: function (state) {
        if (!state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.user_name
      },
      userId: function (state) {
        return state.user.info.user_id
      },
      roleId: function (state) {
        return state.user.info.roleid
      },
      uorId: function (state) {
        return state.user.info.uor_id
      },
      branchName: function (state) {
        return state.user.info.branchId === 1 ? '总公司' : state.user.info.branchName
      },
      branchId: function (state) {
        return state.user.info.branchId
      },
      branchOrgId: function (state) {
        return state.user.info.branchOrgId
      },
      deptName: function (state) {
        return state.user.info.parOrgName
      },
      deptId: function (state) {
        return state.user.info.or_org_id
      }
    }),
    watch: {
      branchList (a, b) {
        this.getDeptList(this.basicInfo.branchId)
      }
    }
  }
</script>






